//条件变量的使用
#include<iostream>
#include<cstring>
#include<unistd.h>
#include<vector>
#include<pthread.h>
const int NUM = 5;
//定义一个全局的条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
int cnt = 10000;
void* threadrun(void* args)
{
    std::string name = static_cast<char*>(args);
    while(true)
    {
        pthread_mutex_lock(&glock);
        pthread_cond_wait(&cond,&glock);
        cnt--;
        std::cout << name << ": " << cnt << std::endl;
        pthread_mutex_unlock(&glock);
        //sleep(1);
    }
    return nullptr;
}
int main()
{
    std::vector<pthread_t> tids;
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        std::string* name = new std::string(); 
        *name = "pthread - " + std::to_string(i);
        pthread_create(&tid,nullptr,threadrun,(char*)name -> c_str());
        std::cout << "创建一个线程成功" << std::endl;
        tids.push_back(tid);
    }
    sleep(3);
    while(true)
    {
        //唤醒线程
        std::cout << "唤醒一个线程..." << std::endl;
        pthread_cond_signal(&cond);
        sleep(2);
    }
    for(auto x : tids)
    {
        pthread_join(x,nullptr);
        std::cout << "等待一个线程成功" << std::endl;
    }
    return 0;
}